package com.boot.security.server.advice;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.boot.security.server.service.ApiAccessCheckService;


@Component
@Aspect
public class SecurityAspect {

	private final Logger log=LoggerFactory.getLogger(getClass());
	
	private static final String USER_ID_NAME="userId";
	
	@Autowired
	private ApiAccessCheckService apiAccessCheckService;
	
	/**
	 * 使用要拦截标注有AdminOnly的注解进行操作
	 */
	@Pointcut("@annotation(com.boot.security.server.annotation.UserOnly)")
	public void UserOnly(){
		
	}
	
	/**
	 * 带@UserOnly注解的方法需要判断权限
	 * @param joinPoint
	 */
	
	@Before("UserOnly()")
	public void check(JoinPoint joinPoint){
		log.info("获取用户参数");
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		Enumeration<String> parameterNames = request.getParameterNames();
		while (parameterNames.hasMoreElements()) {
			String paramName = (String) parameterNames.nextElement();
			String parameter = request.getParameter(paramName);
			log.info("传入的参数为{}={},", paramName,parameter);
			if(paramName.equals(USER_ID_NAME)) {
				//判断是否有访问接口的权限
				apiAccessCheckService.checkAccess(parameter);
			}
		}
	}
}
